import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Image,
  TextInput,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/MaterialIcons';
import ImagePicker from 'react-native-image-crop-picker';

const ProfileScreen = ({ navigation }) => {
  const [userData, setUserData] = useState({
    fullName: '张三',
    email: 'zhangsan@example.com',
    phone: '+86 138 0013 8000',
    dateOfBirth: '1990-01-01',
    country: '中国',
    city: '北京',
    address: '北京市朝阳区xxx路xxx号',
    postalCode: '100000',
  });

  const [isEditing, setIsEditing] = useState(false);
  const [editedData, setEditedData] = useState(userData);
  const [profileImage, setProfileImage] = useState(null);

  const handleEditToggle = () => {
    if (isEditing) {
      setUserData(editedData);
    }
    setIsEditing(!isEditing);
  };

  const handleImageUpload = async () => {
    try {
      const image = await ImagePicker.openPicker({
        width: 300,
        height: 300,
        cropping: true,
        cropperCircleOverlay: true,
      });
      setProfileImage(image.path);
    } catch (error) {
      console.log('Image picker error:', error);
    }
  };

  const profileSections = [
    {
      title: '基本信息',
      fields: [
        { key: 'fullName', label: '姓名', icon: 'person' },
        { key: 'email', label: '邮箱', icon: 'email' },
        { key: 'phone', label: '手机号', icon: 'phone' },
        { key: 'dateOfBirth', label: '出生日期', icon: 'calendar-today' },
      ],
    },
    {
      title: '地址信息',
      fields: [
        { key: 'country', label: '国家', icon: 'public' },
        { key: 'city', label: '城市', icon: 'location-city' },
        { key: 'address', label: '详细地址', icon: 'home' },
        { key: 'postalCode', label: '邮政编码', icon: 'markunread-mailbox' },
      ],
    },
  ];

  const renderField = (field, sectionIndex, fieldIndex) => (
    <View key={field.key} style={styles.fieldContainer}>
      <View style={styles.fieldHeader}>
        <Icon name={field.icon} size={20} color="#a0a0a0" />
        <Text style={styles.fieldLabel}>{field.label}</Text>
      </View>
      {isEditing ? (
        <TextInput
          style={styles.input}
          value={editedData[field.key]}
          onChangeText={(text) => setEditedData({ ...editedData, [field.key]: text })}
          placeholder={`请输入${field.label}`}
          placeholderTextColor="#a0a0a0"
        />
      ) : (
        <Text style={styles.fieldValue}>{userData[field.key]}</Text>
      )}
    </View>
  );

  return (
    <LinearGradient colors={['#1a1a2e', '#16213e']} style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        {/* Header */}
        <View style={styles.header}>
          <TouchableOpacity onPress={() => navigation.goBack()}>
            <Icon name="arrow-back" size={24} color="#fff" />
          </TouchableOpacity>
          <Text style={styles.title}>个人资料</Text>
          <TouchableOpacity onPress={handleEditToggle}>
            <Text style={styles.editButton}>
              {isEditing ? '保存' : '编辑'}
            </Text>
          </TouchableOpacity>
        </View>

        {/* Profile Picture */}
        <View style={styles.profileSection}>
          <TouchableOpacity
            style={styles.profileImageContainer}
            onPress={handleImageUpload}
            disabled={!isEditing}
          >
            {profileImage ? (
              <Image source={{ uri: profileImage }} style={styles.profileImage} />
            ) : (
              <View style={styles.profileImagePlaceholder}>
                <Icon name="account-circle" size={80} color="#a0a0a0" />
              </View>
            )}
            {isEditing && (
              <View style={styles.cameraIcon}>
                <Icon name="camera-alt" size={20} color="#fff" />
              </View>
            )}
          </TouchableOpacity>
          <Text style={styles.profileName}>{userData.fullName}</Text>
          <Text style={styles.profileEmail}>{userData.email}</Text>
        </View>

        {/* Profile Sections */}
        {profileSections.map((section, sectionIndex) => (
          <View key={sectionIndex} style={styles.section}>
            <Text style={styles.sectionTitle}>{section.title}</Text>
            <View style={styles.sectionContent}>
              {section.fields.map((field, fieldIndex) => 
                renderField(field, sectionIndex, fieldIndex)
              )}
            </View>
          </View>
        ))}

        {/* Verification Status */}
        <View style={styles.verificationSection}>
          <Text style={styles.sectionTitle}>身份验证</Text>
          <View style={styles.verificationCard}>
            <View style={styles.verificationHeader}>
              <Icon name="verified-user" size={24} color="#4CAF50" />
              <Text style={styles.verificationTitle}>已验证</Text>
            </View>
            <Text style={styles.verificationText}>
              您的身份验证已通过，享受完整的交易功能
            </Text>
            <TouchableOpacity
              style={styles.verificationButton}
              onPress={() => navigation.navigate('IdentityVerification')}
            >
              <Text style={styles.verificationButtonText}>查看详情</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* Account Actions */}
        <View style={styles.actionsSection}>
          <TouchableOpacity style={styles.actionButton}>
            <Icon name="lock" size={20} color="#fff" />
            <Text style={styles.actionButtonText}>修改密码</Text>
          </TouchableOpacity>
          <TouchableOpacity style={styles.actionButton}>
            <Icon name="delete" size={20} color="#f44336" />
            <Text style={[styles.actionButtonText, { color: '#f44336' }]}>
              删除账户
            </Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </LinearGradient>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollContent: {
    padding: 20,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#fff',
  },
  editButton: {
    color: '#4CAF50',
    fontSize: 16,
    fontWeight: 'bold',
  },
  profileSection: {
    alignItems: 'center',
    marginBottom: 30,
  },
  profileImageContainer: {
    position: 'relative',
    marginBottom: 15,
  },
  profileImage: {
    width: 100,
    height: 100,
    borderRadius: 50,
  },
  profileImagePlaceholder: {
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  cameraIcon: {
    position: 'absolute',
    bottom: 0,
    right: 0,
    backgroundColor: '#4CAF50',
    borderRadius: 15,
    width: 30,
    height: 30,
    justifyContent: 'center',
    alignItems: 'center',
  },
  profileName: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 5,
  },
  profileEmail: {
    fontSize: 16,
    color: '#a0a0a0',
  },
  section: {
    marginBottom: 30,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#a0a0a0',
    marginBottom: 15,
  },
  sectionContent: {
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    borderRadius: 15,
    overflow: 'hidden',
  },
  fieldContainer: {
    paddingVertical: 15,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(255, 255, 255, 0.1)',
  },
  fieldContainer:lastChild: {
    borderBottomWidth: 0,
  },
  fieldHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 5,
  },
  fieldLabel: {
    color: '#a0a0a0',
    fontSize: 14,
    marginLeft: 10,
  },
  fieldValue: {
    color: '#fff',
    fontSize: 16,
  },
  input: {
    color: '#fff',
    fontSize: 16,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(255, 255, 255, 0.2)',
    paddingVertical: 5,
  },
  verificationSection: {
    marginBottom: 30,
  },
  verificationCard: {
    backgroundColor: 'rgba(76, 175, 80, 0.2)',
    borderRadius: 15,
    padding: 20,
  },
  verificationHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  verificationTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#fff',
    marginLeft: 10,
  },
  verificationText: {
    color: '#a0a0a0',
    fontSize: 14,
    marginBottom: 15,
  },
  verificationButton: {
    backgroundColor: '#4CAF50',
    borderRadius: 10,
    paddingVertical: 10,
    paddingHorizontal: 20,
    alignSelf: 'flex-start',
  },
  verificationButtonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: 'bold',
  },
  actionsSection: {
    marginBottom: 20,
  },
  actionButton: {
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    borderRadius: 15,
    padding: 15,
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  actionButtonText: {
    color: '#fff',
    fontSize: 16,
    marginLeft: 10,
  },
});

export default ProfileScreen;
